<?php

class Common_DataTable_Persistence_File extends Common_DataTable_Persistence_Abstract {

    public function __construct(Common_DataTable $obj_datatable, $arr_options = array()) {
        parent::__construct($obj_datatable, $arr_options);
    }
    
    protected function getPersistenceDirectory() {
        
        $str_directory = $this->property__getProperty('persistence_directory', '/tmp/');
        
        if($str_directory[strlen($str_directory)-1] != DIRECTORY_SEPARATOR) {
            $str_directory .= DIRECTORY_SEPARATOR;
        }
        
        return $str_directory;
    }
    
    protected function getPersistenceFile($str_key) {
        return $this->getPersistenceDirectory() . $str_key;
    }
    
    public function store($str_key = null) {
        
        $str_key = (string) $str_key;
        
        if(is_null($str_key) || ($str_key == '')) {
            $str_key = $this->generatePersistenceKey();
        }
        
        $str_file = $this->getPersistenceFile($str_key);
        
        $str_serialise = serialize($this->getDataTable());
        
        $mix = file_put_contents($str_file, $str_serialise);
        if($mix === false) {
            throw new Exception("Persistence file [$str_file] is not writeable.");
        }
        
        return $str_key;
    }
    
    public function retrieve($str_key) {
        
        $obj_datatable = null;
        
        $str_file = $this->getPersistenceFile($str_key);
        
        if(!file_exists($str_file)) {
            throw new Exception("Persistence file [$str_file] does not exist.");
        }
        
        if(!is_readable($str_file)) {
            throw new Exception("Persistence file [$str_file] is not readable.");
        }
        
        $str_serialise = file_get_contents($str_file);
        if(empty($str_serialise)) {
            throw new Exception('Serialised content is empty');
        }
        
        $obj_datatable = unserialize($str_serialise);
        
        return $obj_datatable;
        
    }
    
}

